package ciprian.google;

import ciprian.google.R;
import ciprian.google.transport.NetworkUtilities;
import ciprian.google.transport.TransportAsyncTask;
import ciprian.google.utils.Prefs;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Activity which displays login screen to the user.
 */
public class AuthenticatorActivity extends FragmentActivity implements OnClickListener {

    private static final String TAG = "AuthenticatorActivity";
    private TransportAsyncTask mAuthAsyncTask;

    private TextView mMessage;
    private EditText mPasswordEdit;
    private Button signInButton;

    private EditText mUsernameEdit;

    private DialogFragment waitingDialog;

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate(Bundle icicle) {
        Log.i(TAG, "onCreate(" + icicle + ")");
        super.onCreate(icicle);

        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.login_activity);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
                android.R.drawable.ic_dialog_alert);

        mMessage = (TextView) findViewById(R.id.message);
        mUsernameEdit = (EditText) findViewById(R.id.username_edit);
        mPasswordEdit = (EditText) findViewById(R.id.password_edit);
        signInButton = (Button) findViewById(R.id.signInButton);

        SharedPreferences settings = Prefs.get();
        mUsernameEdit.setText(settings.getString(Constants.PARAM_USERNAME, ""));
        signInButton.setOnClickListener(this);
    }

    /**
     * Handles onClick event on the Submit button. Sends username/password to
     * the server for authentication.
     */
    public void handleLogin() {
        String mUsername = mUsernameEdit.getText().toString();
        String mPassword = mPasswordEdit.getText().toString();
        if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
            mMessage.setText(getText(R.string.login_activity_empty_credentials));
        } else {
            SharedPreferences settings;
            SharedPreferences.Editor editor;

            settings = Prefs.get();
            editor = settings.edit();

            // put token + username in preferences, also put a time stamp.
            editor.putString(Constants.PARAM_USERNAME, mUsername);
            editor.putString(Constants.PARAM_PASSWORD, mPassword);
            editor.putLong(Constants.PARAM_TIME, System.currentTimeMillis());

            editor.commit();

            showProgress();
            // Start authenticating...
            mAuthAsyncTask = NetworkUtilities.attemptAuth(AuthenticatorActivity.this);
        }
    }

    /**
     * Called when response is received from the server for confirm credentials
     * request. See onAuthenticationResult(). Sets the
     * AccountAuthenticatorResult which is sent back to the caller.
     * 
     * @param the
     *            confirmCredentials result.
     */
    protected void finishConfirmCredentials(boolean result) {
        Log.i(TAG, "finishConfirmCredentials()");
        setResult(RESULT_OK, null);
        finish();
    }

    /**
     * Hides the progress UI for a lengthy operation.
     */
    protected void hideProgress() {
        if (waitingDialog.getDialog().isShowing())
            waitingDialog.dismiss();
    }

    /**
     * Called when the authentication process completes (see attemptLogin()).
     */
    public void onAuthenticationResult(int result) {
        Log.i(TAG, "onAuthenticationResult(" + result + ")");
        // Hide the progress dialog
        hideProgress();
        if ((result & NetworkUtilities.RESULT_OK) != 0) {
            finishConfirmCredentials(true);
        } else if ((result & NetworkUtilities.RESULT_NOK) != 0) {
            if ((result & NetworkUtilities.RESULT_AUTHENTICATION_PROBLEM) != 0) {
                // wrong user/pass
                mMessage.setText(getText(R.string.login_activity_loginfail_text_both));
                SharedPreferences settings;
                SharedPreferences.Editor editor;

                settings = Prefs.get();
                editor = settings.edit();
                //login failed ==> remove the password / token from prefs
                editor.putString(Constants.PARAM_PASSWORD, "");
                editor.putString(Constants.PARAM_TOKEN, "");
                editor.commit();
            } else if ((result & NetworkUtilities.RESULT_NETWORK_PROBLEM) != 0) {
                // network issue.
                mMessage.setText(getText(R.string.network_issue_msg));
            } else {
                // other issue.
                mMessage.setText(getText(R.string.network_issue_msg));
            }
        }
    }

    /**
     * Shows the progress UI for a lengthy operation.
     */
    protected void showProgress() {
        waitingDialog = MyDialog.newInstance(MyDialog.DIALOG_TYPE_AUTH_WAITING);
        waitingDialog.show(getSupportFragmentManager(), "dialog");
    }

    /**
     * If the user cancels the operation
     */
    public void onWaitingDialogCancel() {
        Log.i(TAG, "dialog cancel has been invoked");
        if (mAuthAsyncTask != null) {
            mAuthAsyncTask.cancel(true);
            finish();
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.signInButton:
            handleLogin();
            break;
        }
    }
}